<?php
/*
 Plugin Name: Stack Exchange Tags
 Plugin URI: http://www.rainydayinn.com/
 Description: This plugin replace the current tagging system with an StackExchange style tagging system.  Non-admin user will only be able to select existing tags by using the type-ahead box.  Admin user will be able to create new tags on the fly.
 Version: 0.1.0
 Author: Ryan Liu
 Author URI: http://www.rainydayinn.com/
 */

$setags = new SETags();

class SETags
{
	private $dir;
	private $path;
	private $siteurl;
	private $wpadminurl;
	private $version;
	private $upgrade_version;
	private $fields;
	private $options_page;


	/*--------------------------------------------------------------------------------------
	 *
	 *	Constructor
	 *
	 *	@author Ryan Liu
	 *	@since 0.1.0
	 *
	 *-------------------------------------------------------------------------------------*/

	function __construct()
	{
		// set class variables
		$this->path = dirname(__FILE__).'';
		$this->dir = plugins_url('',__FILE__);
		$this->siteurl = get_bloginfo('url');
		$this->wpadminurl = admin_url();
		$this->version = '0.1.0';
		$this->upgrade_version = '0.0.0'; // this is the latest version which requires an upgrade
		add_action('plugins_loaded', array($this, 'pluginInit'));
	}	
	
	function pluginInit() {
		add_action('admin_head', array($this, 'admin_head'));		
		add_action( 'do_meta_boxes', array( $this, 'do_meta_boxes' ) );
		add_action( 'save_post', array( $this, 'save_post_tags' ) );									
	}	
	
	public function admin_head () {
		wp_register_style( 'setags', $this->dir . '/css/setags.css');
		wp_enqueue_style( 'setags' );
			
		wp_register_script( 'setags', $this->dir . '/script/setags.js');
		wp_enqueue_script( 'setags' );
		$posttags = get_the_tags();		
		$tags = array();
		if ($posttags) {
  			foreach($posttags as $tag) {
  				$tags[] = $tag->name;
  			}
		}
		$data = array ('url'=> $this->dir.'/tagsuggest.php', 'tags'=>$tags);		
		wp_localize_script( 'setags', 'tagsuggest',  $data);				
	}
	
	public function do_meta_boxes() {	
		add_meta_box ('setagsdiv', __('Tickers'), array( $this, 'setags_metabox' ), 'post', 'normal', 'high');
	}	
	
	public function save_post_tags ($post_id) {
		$tags = $_POST['setags'];
		wp_set_post_tags( $post_id, $tags );	
	}
	
	public function setags_metabox () {
		require_once ($this->path . '/view/tagbox.php');
	}
}